import React from 'react';
import {connect} from 'dva';
import PropTypes from 'prop-types';
import {Table, Button,Row,Col,Layout, Breadcrumb,DatePicker,Popconfirm,Icon,Input,Card,Modal,message,Tabs,Select} from 'antd';
import TableStyle from '../../styles/TableCss.less';
import style from '../../styles/ResetInput.less';
import PayStyle from '../../styles/Pay.less';
import {Link} from 'dva/router'
import reqwest from 'reqwest';
import {datevali} from '../../utils/Validator.js';
import {range,disabledDate,disabledDateTime } from '../../utils/Date.js'
import moment from 'moment';
import pingpp from 'pingpp-js'
import {reqwest_get,reqwest_post} from '../../utils/Reqwest.js'
const {  Content, Footer } = Layout;
const TabPane = Tabs.TabPane;
const Option = Select.Option;
let start_at=null;
let end_at=null;
class Pay extends React.Component{
  constructor(props){
    super(props);
    let _this=this;
    this.state={
      data:[],
      visible:false,
      loading:false,
      visible1:false,
      wallet:undefined,
      // wallet:[],
      recharge:null,
      withdraw:null,
      bank_cards:[],
      bank_id:null,
      // pagination:{},
      columns:[{
        title:"时间",
        dataIndex:'timer',
        render: (text) => this.formatTimer(text)
      },{
        title:'操作',
        dataIndex:'operation'
      },{
        title:'金额',
        dataIndex:'money'
      }]
    }
  }
  getWallet(params={}){
    let _data=[];
    let _random;
    this.setState({loading:true})
    reqwest_get('/api/wallets/me',{
        access_token:localStorage['token'],
        page:params.current
      },(data) => {
        const pagination = { ...this.state.pagination };
        pagination.total = data.total;
        // console.log(data);
        this.setState({wallet:data.wallet})
        for(let i of data.list){
          _data.push({
            key:Math.random()*1,
            timer:i.time,
            operation:i.transfer,
            money:'¥'+i.amount
          })
        }
        this.setState({data:_data,pagination: pagination,});
     })
    this.setState({loading:false})
  }
  loadServer() {
    // console.log('params:', params);
    let _data=[];
    let _this = this;
    if(this.state.recharge!=null){
      reqwest({
        url: window.host+'/api/wallets/recharge',
        method: 'post',
        crossOrigin: true,
        // headers:AUTH_KEY,
        // contentType: 'application/json',
        data:{
          access_token:window.localStorage['token'],
          amount:_this.state.recharge,
          trade_type:'alipay_pc_direct'
        },
        type: 'json',
      }).then((data)=>{
           if(data.status=='success'){
         pingpp.createPayment(data.data.charge, function(result, err){
           // alert(result);
           if (result == "success") {
             // 只有微信公众账号 wx_pub 支付成功的结果会在这里返回，其他的支付结果都会跳转到 extra 中对应的 URL。

             console.log(1)
           } else if (result == "failed") {
              message.error(data.msg,0.6)
             // charge 不正确或者微信公众账号支付失败时会在此处返回
           } else if (result == "cancel") {
             // 微信公众账号支付取消支付
             message.error('取消支付',0.6)
           }
         });
        }
      }).fail((data)=>{

      })
    }
  }
  onWithdrawOk(){
    let _this = this;
      // console.log(values);
      if(this.state.bank_id!=null&&this.state.withdraw!=null){
        reqwest_post('/api/wallets/withdraw',{
          access_token:window.localStorage['token'],
          amount:_this.state.withdraw,
          bank_card_id:_this.state.bank_id
        },(data)=>{
          if(data.status=='success'){
            message.success(data.msg,0.6);

          }else{
            message.warning(data.msg,0.5)
          }
        })
      }
  }
  componentWillMount(){
    // this.fetch({page:1});
    console.log(this.props.location.current)
    this.getWallet({current:1})
    this.getBankCard()
  }
  menuClick(e){
    // console.log(e.item.props.value)
    this.setState({dropDown:e.item.props.value});
  }
  handleOk(){
    this.loadServer();
  }
  formatNumber = (n) => {
    n = n + '';
    return n[1] ? n : '0' + n;
  }
  formatTimer = (time) => {
    console.log('timetime', time)
    const _this = this;
    const date = new Date(time * 1000);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();

    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    return [year, month, day].map(_this.formatNumber.bind(_this)).join('/') + ' ' + [hour, minute, second].map(_this.formatNumber.bind(_this)).join(':');
  }
  getBankCard(){
    reqwest_get('/api/users/bank_cards',{
      access_token:window.localStorage['token']
    },(data)=>{
      if(data.status=='success'){
        console.log(data)
        this.setState({bank_cards:data.list})
      }else{
        message.warning(data.msg,0.3)
      }
    });
  }
  handleTableChange(e){
    // console.log(e)
    this.getWallet(e)
  }
  render(){
    console.log(this.state.wallet)
    const { selectedRowKeys,data,pagination,loading,dropDown,columns ,bank_cards,wallet} = this.state;
    let Cards = bank_cards.map((data,index)=>{
      return(
        <Option key={data.id} value={''+data.id}>
          {data.account+' '+data.code}
        </Option>
      )
    })
    return(
      <Layout style={{background:'#fff',height:'100%' }}>
        <Content>
          <Row type='flex'>
            <Col span={7} xl={{span:7}} xs={7} style={{padding:'24px 25px 24px'}}>
              <Breadcrumb style={{fontSize:14}}>
                <Breadcrumb.Item>我的钱包</Breadcrumb.Item>
              </Breadcrumb>
            </Col>
            <Col xl={{span :3,offset:13}} lg={{span:3,offset:13}} md={{span:3,offset:13}} sm={{span:3,offset:13}} style={{lineHeight:'60px',textAlign:'right'}}>
              <Link to={{pathname:'/app/bank_list',query:{current:this.props.location.query.current}}}>我的银行卡</Link>
            </Col>
          </Row>
          <Layout className={`${TableStyle.tb_serbor}`}>
            <Row type='flex' className={`${TableStyle.tb_ser}`}>
              <Col span={6}>
              </Col>
              <Col span={7} offset={11} style={{textAlign:'right'}}>
                <span>
                  <Link onClick={()=>{this.setState({visible:true})}}>充值</Link>
                  <a><span className="ant-divider" /></a>
                  <Link onClick={()=>{this.setState({visible1:true})}}>提现</Link>
                </span>
              </Col>
             </Row>
            <Card className={`${PayStyle.card}`}>
              <span>
                <p>金额</p><p>{wallet===undefined?0:wallet.amount}</p>
              </span>
              <span>
                <p>总提成</p><p>{wallet===undefined?0:wallet.income}</p>
              </span>
            </Card>
          </Layout>
        </Content>
        <Content style={{padding:'0px 30px'}}>
          <Table columns={columns}
            dataSource={data}
            pagination={pagination}
            loading={loading}
            onChange={this.handleTableChange.bind(this)}/>
        </Content>
        <Modal
          onOk={this.loadServer.bind(this)} title='充值'  visible={this.state.visible}  onCancel={()=>{this.setState({visible:false,recharge:null})}}>
            <div style={{margin:'0 auto',width:'350px'}}>
              <Input min={0} onChange={(e)=>{this.setState({recharge:e.target.value});console.log(e.target.value)}} className={`${style.ncc_reset_input}`} type='number' placeholder='充值金额'/>
            </div>
        </Modal>
        <Modal
          onOk={this.onWithdrawOk.bind(this)} title='提现'  visible={this.state.visible1}  onCancel={()=>{this.setState({visible1:false,bank_id:null,withdraw:null})}}>
            <div style={{margin:'0 auto',width:'350px'}} className={`${style.reset_col}`}>
              <Select style={{width:'100%',margin:'15px 0px',}}  className={`${style.ncc_reset_border}`} optionFilterProp='children' showSearch placeholder='银行卡' onChange={(e)=>{this.setState({bank_id:e})}}>
                {Cards}
              </Select>
              <Input min={0} onChange={(e)=>{this.setState({withdraw:e.target.value});console.log(e.target.value)}} className={`${style.ncc_reset_input}`} type='number' placeholder='提现金额'/>
            </div>
        </Modal>
      </Layout>
    )
  }
}
              // <span>
              //   <p>金额</p><p>{this.state.wallet.amount}</p>
              // </span>
              // <span>
              //   <p>总提成</p><p>{this.state.wallet.income}</p>
              // </span>
  // <div style={{width:'300px',marginBottom:30}}  className={`${style.date_reset_input}`}>
            //   <DatePicker
            //     placeholder='交易记录时间'
            //     onChange={(e,b)=>{this.setState({_date:b})}}
            //     style={{width:'100%'}}
            //     format="YYYY-MM-DD"
            //     disabledDate={disabledDate}
            //     showTime
            //   />
            // </div>
            // <Table columns={columns}
            // className={`${TableStyle.ncc_table}`}
            // key='ttt'
            //   dataSource={data} onRowClick={this.handleRowClick}
            //   pagination={pagination}
            //   loading={loading}
            //   onChange={this.handleTableChange.bind(this)}
            // />
export default connect()(Pay);
